#!/bin/bash

# For help customizing this script, read:
# http://tiny/a6md3511/Third-Party_custom-build

# Fail when commands exit unsuccesfully.
set -o errexit

# Fail when using an undefined variable.
set -o nounset

# Fail if commands fail as part of a pipeline.
set -o pipefail

SRC_DIR=`pwd`
BUILD_DIR="$SRC_DIR/build"
PRIVATE_BUILD_DIR="$BUILD_DIR/private/build"
INSTALL_DIR="$BUILD_DIR/private/install"

# Add a 'clean' target for convenience.
if [[ $# > 0 ]]; then
  if [[ "$1" == "clean" ]]; then
    echo "Cleaning build output..."
    rm -rf "$BUILD_DIR"/*
    exit 0
  fi
fi

echo "Getting configuration values from Brazil"
eval "$(cflags -format sh)"

# Make sure we can use the build tools
BUILDTOOLS_BIN_PATH="$(brazil-path tooldirect.bin)"
BUILDTOOLS_LIB_PATH="$(brazil-path tooldirect.lib)"
export PATH="$PATH:$BUILDTOOLS_BIN_PATH"
export LD_LIBRARY_PATH="$BUILDTOOLS_LIB_PATH"

# Add calls to brazil-path here to get other configure options
LIBFARM="$(brazil-path build.libfarm)"
export PKG_CONFIG_LIBDIR="$LIBFARM/lib/pkgconfig"
export CFLAGS="$CFLAGS -I$LIBFARM/include"
export CXXFLAGS="$CXXFLAGS -I$LIBFARM/include"
export LDFLAGS="$LDFLAGS -L$LIBFARM/lib -Wl,-rpath-link,$LIBFARM/lib"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$(brazil-path build.lib)"

# Make sure we can find the Glib mkenums build script
export PATH="$LIBFARM/bin:$PATH"

# GDB in AL2012 (v7.2) does not support dwarf-4
export CFLAGS="$CFLAGS -gdwarf-3"
export CXXFLAGS="$CXXFLAGS -gdwarf-3"

# Work around toolchain issue (__locale_t undefined)
export CFLAGS="$CFLAGS -D__USE_XOPEN2K8 -D_GNU_SOURCE"
export CXXFLAGS="$CXXFLAGS -D__USE_XOPEN2K8 -D_GNU_SOURCE"

# Force linking against librt to make sure clock_gettime is found
export LDFLAGS="$LDFLAGS -lrt"

echo "Running third-party build"
meson --libdir=lib --prefix $INSTALL_DIR $PRIVATE_BUILD_DIR -Ddisable_gtkdoc=true -Ddisable_examples=true
ninja -v -C $PRIVATE_BUILD_DIR install

echo "Stripping rpaths..."
BIN_DIR="$INSTALL_DIR/bin"
LIB_DIR="$INSTALL_DIR/lib"
for file in $(find -H "$BIN_DIR" "$LIB_DIR" | sort)
do
  if [[ "$(chrpath -l $file 2> /dev/null)" =~ RPATH= ]]; then
    echo "Stripping rpath from $file..."
    chrpath -d "$file"
  fi
done

echo "Copying install artifacts to Brazil locations..."
cp -rf "$INSTALL_DIR"/* "$BUILD_DIR"
# vim: set ft=sh ts=2 sw=2 tw=79 :
